import type { Router } from "vue-router"
import { useAuthStore, } from "@/store"
import nprogress from "nprogress";
import "nprogress/nprogress.css";
import { sysTitle, authRouteMode } from "@/common/config"
import {primaryColor_hex,primaryColorFade,globalLoadingMaskBgColor} from "@/theme/config"
import { constRoutes } from "@/router"
import { initLoading, type LoadingType, type CircularOptionsType } from 'web-loading'

const getNoLoginPaths = () => constRoutes.map(v => v.path)

export default (router: Router) => {
  router.beforeEach(async (to, from, next) => {
    //console.log(router.getRoutes())
    //console.log(to.name,to.fullPath)
    nprogress.start()
    if (authRouteMode == 'local') { next(); return }
    else {
      if (getNoLoginPaths().includes(to.path)) { next(); return }
      const authStore = useAuthStore()
      // 手动f5刷新浏览器，addRoute方式添加的路由配置会被vue-router清除
      if (authStore.routeConfig.length) { next(); return }
      else {
        webLoading.loading(document.body)
        const res = await authStore.setAuth()
        if (res.code == 200) {
          res.accessedRoutes.forEach((v: any) => router.addRoute(v))
          await new Promise<any>(rel => { setTimeout(() => { rel('') }, 10) })
          next(to.fullPath)
          console.log('accessedRoutes', res.accessedRoutes)
          // console.log('accessedRoutes',router.getRoutes())
        } else next()  // 断网或者服务器异常
      }
     
    }
  })

  router.afterEach((to, _from) => {
    webLoading.close()
    document.title = `${to.meta.title} - ${sysTitle}`
    nprogress.done()
  })
}


// https://tommyrunner.github.io/web-loading/document/use.html
export const webLoading: LoadingType = initLoading({
  "type": "dom", "model": "Circular", "text": sysTitle, "textGap": 8, "fontSize": 16, "fontFamily": "Microsoft YaHei", "delay": 21, "delayInto": 320, "notFeel": 0, "zIndex": "2001", "themeColor": primaryColor_hex, "bgColor": globalLoadingMaskBgColor, "shadowColor":primaryColorFade(0.6) , "shadowOffsetX": 2, "shadowOffsetY": 2, "shadowBlur": 5, "pointerEvents": false, "optimization": false, "arcGap": 8, "action": "rotate", "arcSize": 8, 
 //  "arcColors": ["#ec7546", "#8364a4", "#ff6c6e", "#5bc6ab"] ,
  "arcColors": [primaryColor_hex,primaryColor_hex,primaryColor_hex,primaryColor_hex] ,
} as CircularOptionsType)


nprogress.configure({
 // 动画方式
 easing: "ease",
 // 递增进度条的速度
 speed: 500,
 // 是否显示加载ico
 showSpinner: false,
 // 自动递增间隔
 trickleSpeed: 200,
 // 初始化时的最小百分比
 minimum: 0.3,
});

